package com.merlin.demo_wellshape.controller;

import com.merlin.demo_wellshape.pojo.CheckInRecord;
import com.merlin.demo_wellshape.pojo.ResponseMessage;
import com.merlin.demo_wellshape.pojo.User;
import com.merlin.demo_wellshape.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
import java.util.Map;

@RestController // 接口方法返回对象，转换成JSON数据
@RequestMapping("/api") // 映射路径
public class CheckInController {

    @Autowired // 自动注入
    private UserService userService;

    // 签到
    @PostMapping("/check-in") // URL：localhost:8080/api/check-in  method:post
    public ResponseMessage<Void> checkIn(@RequestParam String userPhone) {
        User user = userService.getUserByPhone(userPhone);
        if (user == null) {
            return new ResponseMessage<>(404, "找不到用户", null);
        }

        LocalDate today = LocalDate.now();
        if (userService.hasCheckedInToday(user, today)) {
            return new ResponseMessage<>(400, "今天已经签到过了", null);
        }

        CheckInRecord checkInRecord = new CheckInRecord();
        checkInRecord.setUser(user);
        checkInRecord.setCheckInDate(LocalDate.now());

        userService.saveCheckInRecord(checkInRecord);

        return new ResponseMessage<>(200, "打卡成功~", null);
    }

    // 获取签到信息
    @GetMapping("/check-in-info") // URL：localhost:8080/api/check-in-info  method:get
    public ResponseMessage<Map<String, Object>> getCheckInInfo(@RequestParam String userPhone, @RequestParam int year, @RequestParam int month) {
        YearMonth yearMonth = YearMonth.of(year, month);
        LocalDate startDate = yearMonth.atDay(1);
        LocalDate endDate = yearMonth.atEndOfMonth();

        User user = userService.getUserByPhone(userPhone);
        if (user == null) {
            return new ResponseMessage<>(404, "找不到用户", null);
        }

        List<CheckInRecord> checkInRecords = userService.getCheckInRecordsByUserAndDateRange(user, startDate, endDate);

        int consecutiveDays = 0;
        int totalDays = checkInRecords.size();
        List<LocalDate> checkInDates = checkInRecords.stream()
                .map(CheckInRecord::getCheckInDate)
                .toList();
        // 计算连续签到天数
        if (!checkInDates.isEmpty()) {
            consecutiveDays = 1; // 初始化为1，因为至少有一个签到记录
            for (int i = 1; i < checkInDates.size(); i++) {
                if (checkInDates.get(i).isEqual(checkInDates.get(i - 1).minusDays(1))) {
                    consecutiveDays++;
                } else {
                    break;
                }
            }
        }
        Map<String, Object> data = Map.of(
                "consecutiveDays", consecutiveDays,
                "totalDays", totalDays,
                "checkInDates", checkInDates
        );
        return new ResponseMessage<>(200, "获取签到信息成功", data);
    }

    // 补签接口：插入指定日期的签到记录
    @PostMapping("/make-up-check-in") // URL：localhost:8080/api/make-up-check-in  method:post
    public ResponseMessage<LocalDate> makeUpCheckIn(@RequestParam String userPhone, @RequestParam int year, @RequestParam int month, @RequestParam int day) {
        LocalDate checkInDate = LocalDate.of(year, month, day);

        User user = userService.getUserByPhone(userPhone);
        if (user == null) {
            return new ResponseMessage<>(404, "找不到用户", null);
        }

        if (userService.hasCheckedInToday(user, checkInDate)) {
            return new ResponseMessage<>(400, "该日期已经签到过了", null);
        }

        try {
            userService.insertCheckInRecords(userPhone, checkInDate);
            return new ResponseMessage<>(200, "签到记录插入成功", checkInDate);
        } catch (Exception e) {
            return new ResponseMessage<>(500, "签到记录插入失败: " + e.getMessage(), checkInDate);
        }
    }

    // 删除签到记录接口
    @DeleteMapping("/delete-check-in") // URL：localhost:8080/api/delete-check-in  method:delete
    public ResponseMessage<Void> deleteCheckIn(@RequestParam String userPhone, @RequestParam int year, @RequestParam int month, @RequestParam int day) {
        LocalDate checkInDate = LocalDate.of(year, month, day);

        User user = userService.getUserByPhone(userPhone);
        if (user == null) {
            return new ResponseMessage<>(404, "找不到用户", null);
        }

        boolean isDeleted = userService.deleteCheckInRecord(user, checkInDate);
        if (isDeleted) {
            return new ResponseMessage<>(200, "签到记录删除成功", null);
        } else {
            return new ResponseMessage<>(404, "签到记录不存在", null);
        }
    }
}
